package com.aatattoo.light_food_service.controller;

import com.aatattoo.light_food_service.entity.*;
import com.aatattoo.light_food_service.enumeration.ConstantType;
import com.aatattoo.light_food_service.service.*;
import com.aatattoo.light_food_service.utils.SortListUtil;
import com.aatattoo.light_food_service.utils.TimeUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.ls.LSInput;

import java.util.*;


@Controller
@ResponseBody
@RequestMapping("/food")
public class FoodController {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RemindService remindService;
    @Autowired
    private UserService userService;
    @Autowired
    private DynamicService dynamicService;
    @Autowired
    private DynamicTagService dynamicTagService;
    @Autowired
    private MappingTagService mappingTagService;
    @Autowired
    private DynamicImgService dynamicImgService;
    @Autowired
    private UserFollowService userFollowService;
    @Autowired
    private LikeService likeService;
    @Autowired
    private FoodService foodService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private ReplyService replyService;
//    查询食物，根据类型
    @GetMapping("/list/{type}")
    public Map<String,Object> getFood(@PathVariable("type")int type){
        List<Object> foodList = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        List<Food> foods= foodService.selectFoodByType(type);
        foods.forEach(food -> {
            Map<String,Object> foodMap = new LinkedHashMap<>();
            foodMap.put("id",food.getId());
            foodMap.put("name",food.getName());
            foodMap.put("address",food.getPhoto());
            foodList.add(foodMap);
        });
        map.put("FoodType",foodList);
        return map;
    }
    //查询食物详情的接口
    @GetMapping("/details/{id}")
    public Map<String,Object> getFoodDetails(@PathVariable("id")int id,@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        //用于最后存储食物的详情
        Map<String,Object> foodMap = new LinkedHashMap<>();
        //储存查询出律的食谱

        //储存处理好之后的食谱
        List<Object> obj = new ArrayList<>();
        //好处和坏处
        List<GoodUse> goodUses = foodService.selectGoodUseByFoodId(id);
        Food food = foodService.selectFooDetails(id);
        //添加食物的浏览记录
        Recording recording = new Recording();
        recording.setParentId(food.getId());
        recording.setType(1);
        recording.setUserId(userId);
        if (foodService.inRecording(recording) == 1){
            foodService.upRecording(recording);
        }else{
            foodService.addRecording(recording);
        }

        List<Recipes> recipes = foodService.selectCookFoodByFoodId(id);
        foodMap.put("GoodUse",goodUses);
        foodMap.put("id",food.getId());
        foodMap.put("name",food.getName());
        foodMap.put("type",food.getType());
        foodMap.put("calorie",food.getCalorie());
        foodMap.put("protein",food.getProtein());
        foodMap.put("fat",food.getFat());
        foodMap.put("fiber",food.getFiber());
        foodMap.put("carbohydrate",food.getCarbohydrate());
        foodMap.put("fit",food.getFit());
        foodMap.put("unsuited",food.getUnsuited());
        foodMap.put("photo",food.getPhoto());
        recipes.forEach(cookFood ->{
                Map<String,Object> cookMap = new LinkedHashMap<>();
                cookMap.put("id",cookFood.getId());
                cookMap.put("name",cookFood.getName());
                cookMap.put("photo",cookFood.getPhoto());
                obj.add(cookMap);
                });
        foodMap.put("CookFood",obj);
        return foodMap;
    }
    //食谱详情
    @GetMapping("/cook/{id}")
    public Map<String,Object> getCookFood(@PathVariable("id") int id,@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        int count;//记录收藏数
        int flag;//当前用户是否收藏该食谱
        //存放最终返回的数据
        Map<String,Object> map = new LinkedHashMap<>();
        //食谱的基本数据
        Recipes recipes = foodService.selectRecipesById(id);
        //添加浏览记录 先查询是否存在
        Recording recording = new Recording();
        recording.setParentId(recipes.getId());
        recording.setType(2);
        recording.setUserId(userId);
        if (foodService.inRecording(recording) == 1){
            foodService.upRecording(recording);
        }else{
            foodService.addRecording(recording);
        }
        //食物的用量
        List<Meterials> meterials = foodService.selectMeterials(id);
        Collect collect = new Collect();
        collect.setParentId(recipes.getId());
        collect.setUserId(userId);
        collect.setType(1);
        //count存放收藏数量
        count = foodService.collectCount(collect);
        //flag存放用户是否收藏
        flag = foodService.inCollect(collect);
        map.put("id",recipes.getId());
        map.put("name",recipes.getName());
        map.put("method",recipes.getMethod());
        map.put("more",recipes.getMore());
        map.put("photo",recipes.getPhoto());
        map.put("use",meterials);
        map.put("count",count);
        map.put("flag",flag);
        return map;
    }
    //收藏
    @PostMapping("/collect")
    public int insertCollect(@RequestBody Collect collect,@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        collect.setUserId(userId);
        return foodService.insertCollect(collect);
    }
    //取消收藏
    @PostMapping("/delCollect")
    public int deleteCollect(@RequestBody Collect collect,@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        collect.setUserId(userId);
        return foodService.deleteCollect(collect);
    }
    //食物金字塔
    @GetMapping("/getPyramid")
    public Map<String,Object> getPyramid(){
        List<Object> list = new LinkedList<>();
        Map<String,Object> map0 = new LinkedHashMap<>();
        Map<String,Object> map = new LinkedHashMap<>();
        Map<String,Object> mapOne = new LinkedHashMap<>();
        Map<String,Object> map2 = new LinkedHashMap<>();
        Map<String,Object> map3 = new LinkedHashMap<>();
        Map<String,Object> map4 = new LinkedHashMap<>();
        map0.put("title","食物金字塔");
        map0.put("tPhoto","food/img/jinzita.jpg");
        mapOne.put("photo","food/img/1.jpg");
        map2.put("photo","food/img/2.jpg");
        map3.put("photo","food/img/3.jpg");
        map4.put("photo","food/img/4.jpg");
        list.add(mapOne);
        list.add(map2);
        list.add(map3);
        list.add(map4);
        map.put("Top",map0);
        map.put("massage",list);
        return map;
    }
    //查找营养素的信息
    @GetMapping("/trophic")
    public Map<String,Object> getTrophic(){
        Map<String,Object> map = new LinkedHashMap<>();
        Map<String,Object> title = new LinkedHashMap<>();
        List<Object> list = new ArrayList<>();
        List<Trophic> trophics = foodService.getTrophic();
        trophics.forEach( trophic -> {
            Map<String,Object> map1 = new LinkedHashMap<>();
            map1.put("name",trophic.getName());
            map1.put("efficacy",trophic.getEfficacy());
            map1.put("symptoms",trophic.getSymptoms());
            list.add(map1);
        });
        title.put("title","营养素参考表");
        title.put("photo","food/img/yingyangsu.jpeg");
        map.put("top",title);
        map.put("massage",list);
        return map;
    }
    //查找不建议搭配表
    @GetMapping("/common")
    public Map<String,Object> getCommon(){
       Map<String,Object> map = new LinkedHashMap<>();
       Map<String,Object> userMap = new LinkedHashMap<>();
       List<Common> list = foodService.getCommon();
       List<Object> list1 = new ArrayList<>();
       list.forEach(common -> {
           Map<String,Object> listMap  = new LinkedHashMap<>();
           listMap.put("up",common.getFood());
           listMap.put("down",common.getNoFood());
           list1.add(listMap);
       });
       userMap.put("name","不建议搭配表");
       userMap.put("photo","food/img/changshi.jpg");
       map.put("top", userMap);
       map.put("list",list1);
       return map;
    }
    //查找收藏列表   ok
    @GetMapping("/listCollect/{type}")
    public Map<String,Object> getCollect(@PathVariable("type") int type, @RequestHeader("token")String token) {
        int userId = tokenService.analysisUserId(token);
        List<Object> list = new ArrayList<>();
        Map<String,Object> reMap = new HashMap<>();
        List<Dynamic> dynamicList = new ArrayList<>();
        Collect collect = new Collect();
        collect.setType(type);
        collect.setUserId(userId);
        //获取收藏列表的id
        List<Collect> ids = foodService.getCollect(collect);
        if (type == 1) {
            //查找食谱收藏
            ids.forEach(collects -> {
                int id = collects.getParentId();
                Recipes recipes = foodService.getRecipes(id);
                Map<String,Object> map = new HashMap<>();
                map.put("id", recipes.getId());
                map.put("name", recipes.getName());
                map.put("photo", recipes.getPhoto());
                list.add(map);
            });
            reMap.put("recipes",list);
        } else  {
            //查找动态收藏
            ids.forEach(collects->{
                int id = collects.getParentId();
                Dynamic dynamic = dynamicService.findById(id);
                if (dynamic!=null){
                    dynamicList.add(dynamic);
                }
            });

            reMap = pagingQuery(dynamicList,userId,userId,1);
        }
        return reMap;
    }
    //查询浏览记录   ok
    @GetMapping("getRecoding/{type}")
    public List<Object> selectRecoding(@PathVariable("type") int type, @RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        List<Object> list = new ArrayList<>();
        Recording recording = new Recording();
        recording.setUserId(userId);
        recording.setType(type);
        List<Recording> idList = foodService.selectId(recording);
        if (type == 1){
            idList.forEach(id->{
                Map<String,Object> map = new HashMap<>();
                Food food = foodService.selectRecordingFood(id.getParentId());
                map.put("id",food.getId());
                map.put("name",food.getName());
                map.put("photo",food.getPhoto());
                list.add(map);
            });
        }else{
            idList.forEach(id->{
                Map<String,Object> map = new HashMap<>();
                Recipes recipes = foodService.selectRecordingRecipes(id.getParentId());
                map.put("id",recipes.getId());
                map.put("name",recipes.getName());
                map.put("photo",recipes.getPhoto());
                list.add(map);
            });
        }
        return list;
    }
    //查询  search
    @GetMapping("search/{type}/{name}")
    public List<Object> search(@PathVariable("name") String name,@PathVariable("type")int type){
        List<Object> list = new ArrayList<>();
        if (type == 1){//查询食物
            List<Food> foodList = foodService.searchFood(name);
            foodList.forEach(food -> {
                Map map = new HashMap<>();
                map.put("id",food.getId());
                map.put("photo",food.getPhoto());
                map.put("name",food.getName());
                map.put("calorie",food.getCalorie()+"千卡"+"/每100g");
                list.add(map);
            });
        }else if(type == 2){ //查询食谱
            List<Recipes> recipesList = new ArrayList<>();
            recipesList = foodService.searchRecipes(name);
            recipesList.forEach(recipes -> {
                Map map = new HashMap<>();
                map.put("id",recipes.getId());
                map.put("name",recipes.getName());
                map.put("photo",recipes.getPhoto());
                list.add(map);
            });
        }
        return list;
    }

    //下面这四个就是剩下的接口   都携带token
    //推荐食物    type表示  为1 根据卡路里顺序  低卡食物，2  根据蛋白质逆序，高蛋白食物    3    根据脂顺序  低脂肪食物
    // 4 膳食纤维含量多   5  低糖食物/低碳水化合物
    //地址http://8.130.48.173:8081/referralFood/{type}  id:id  name:名字  photo：图片 calorie：卡路里
    @GetMapping("referralFood/{type}")
    public List<Object> foodReferral(@PathVariable("type")int type){
        //全部食物信息   为1 根据卡路里顺序，2  根据蛋白质逆序，3    根据脂顺序   5  高碳水化合物  6  粗纤维逆序
        List<Food> foodList = foodService.allFood();
        ArrayList<Object> mapList = new ArrayList<>(); //排序封装成map之后返回成为一个列表
        SortListUtil<Food> foodSortListUtil = new SortListUtil<>();
        switch (type){
            case 1:
                foodSortListUtil.sort(foodList,"getCalorie",null);
                for (int i =0 ;i < 6;i++)
                {
                    Food food = foodList.get(i);
                    HashMap<String, Object> foodMap = new HashMap<>();
                    foodMap.put("id",food.getId());
                    foodMap.put("name",food.getName());
                    foodMap.put("photo",food.getPhoto());
                    foodMap.put("calorie",food.getCalorie());
                    mapList.add(foodMap);

                }
                break;
            case 2:
                foodSortListUtil.sort(foodList,"getProtein","desc");
                for (int i =0 ;i < 6;i++)
                {
                    Food food = foodList.get(i);
                    HashMap<String, Object> foodMap = new HashMap<>();
                    foodMap.put("id",food.getId());
                    foodMap.put("name",food.getName());
                    foodMap.put("photo",food.getPhoto());
                    foodMap.put("calorie",food.getCalorie());
                    mapList.add(foodMap);
                }
                break;
            case 3:
                foodSortListUtil.sort(foodList,"getFat",null);
                for (int i =0 ;i < 6;i++)
                {
                    Food food = foodList.get(i);
                    HashMap<String, Object> foodMap = new HashMap<>();
                    foodMap.put("id",food.getId());
                    foodMap.put("name",food.getName());
                    foodMap.put("photo",food.getPhoto());
                    foodMap.put("calorie",food.getCalorie());
                    mapList.add(foodMap);
                }
                break;
            case 4:
                foodSortListUtil.sort(foodList,"getFiber","desc");
                for (int i =0 ;i < 6;i++)
                {
                    Food food = foodList.get(i);
                    HashMap<String, Object> foodMap = new HashMap<>();
                    foodMap.put("id",food.getId());
                    foodMap.put("name",food.getName());
                    foodMap.put("photo",food.getPhoto());
                    foodMap.put("calorie",food.getCalorie());
                    mapList.add(foodMap);
                }
                break;
            case 5:
                foodSortListUtil.sort(foodList,"getCarbohydrate",null);
                for (int i =0 ;i < 6;i++)
                {
                    Food food = foodList.get(i);
                    HashMap<String, Object> foodMap = new HashMap<>();
                    foodMap.put("id",food.getId());
                    foodMap.put("name",food.getName());
                    foodMap.put("photo",food.getPhoto());
                    foodMap.put("calorie",food.getCalorie());
                    mapList.add(foodMap);
                }
                break;
        }
        return mapList;
    }

    //全部食谱    count:总页数  pageNum：当前页数  id：id  name：名字  photo：照片    地址http://8.130.48.173:8081/selectAllRecipes/{pageNum}
    @GetMapping("selectAllRecipes/{pageNum}")//pageNum访问页数
    public List<Object> allRecipes(@PathVariable("pageNum")int pageNum){
        PageHelper.startPage(pageNum,10);//设置分页访问页数和一页数据的大小
        ArrayList<Object> reList = new ArrayList<>();//最终返回的数据列表
        List<Recipes> list = foodService.allRecipes();
        PageInfo pageInfo = new PageInfo(list);
        HashMap<String, Object> pageMap = new HashMap<>();//分页结果
        int pageCount = pageInfo.getPages();
        int pageNumbers = pageInfo.getPageNum();
        pageMap.put("count",pageCount);
        pageMap.put("pageNum",pageNumbers);
        reList.add(pageMap);
        list.forEach(recipesList->{
            HashMap<String, Object> recipesMap = new HashMap<>();//放到循环里面每一次都需要重置数据   得到的食谱数据
            recipesMap.put("id",recipesList.getId());
            recipesMap.put("name",recipesList.getName());
            recipesMap.put("photo",recipesList.getPhoto());
            reList.add(recipesMap);
    });

        return reList;
    }

    //推荐食谱  地址http://8.130.48.173:8081/newRecipes  id:id  name:名字  photo:图片  method:做的方法
    @GetMapping("/newsRecipes")
    public List<Object> newsRecipes(){
        ArrayList<Integer> idList = new ArrayList<>();
        ArrayList<Object> ref = new ArrayList<>();
        idList.add(1);
        idList.add(6);
        idList.add(8);
        idList.add(14);
        idList.add(15);
        idList.add(30);
        idList.add(35);
        idList.add(47);
        idList.add(50);
        idList.add(53);
        List<Recipes> recipes = foodService.newsRecipes(idList);
        recipes.forEach(recipe -> {
            HashMap<String, Object> map = new HashMap<>();
            map.put("id",recipe.getId());
            map.put("name",recipe.getName());
            map.put("photo",recipe.getPhoto());
            map.put("method",recipe.getMethod());
            ref.add(map);
        });
            return ref;
    }
    //食物资讯  order  是顺序   1 代表 资讯1   2.。。。。。     返回值只有一个图片地址
    //地址http://8.130.48.173:8081/zixun/{order}
    @GetMapping("zixin/{order}")
    public String getNews(@PathVariable("order")int order){
        String name;//图片的名字，直接返回名字就可以了
        if (order == 1){
            name = "/food/img/zixun1.png";
        } else if (order == 2) {
            name = "/food/img/zixun2.png";
        }else {
            name = "food/img/zixun3.png";
        }
        return name;
    }

    /**
     *
     * @param dynamicList
     * @param myId
     * @param type 0,1-每条动态都携带用户参数
     *             2-我的动态，只显示一天用户参数，我的
     *             3-只显示一条用户参数（详细）其他用户

     * @return
     */
    private  Map<String, Object> pagingQuery(List<Dynamic> dynamicList,int myId,int othUserId,int type){
        // 封装分页查询结果到 PageInfo 对象中以获取相关分页信息
        PageInfo pageInfo = new PageInfo( dynamicList );
        Map<String,Object> mapData=new LinkedHashMap<>();
        List<Object> mapList=new ArrayList<>();
        Map<String,Object> pageMap=new LinkedHashMap<>();
        pageMap.put("pageCount",pageInfo.getPages());
        pageMap.put("pageNumber",pageInfo.getPageNum());
        mapData.put("page",pageMap);
//       获取个人动态或指定用户动态，只需要提供一次用户信息
        Map<String,Object> userMap=new LinkedHashMap<>();
        if (type==3){
            if (!mapData.containsKey("user")){
                //获取发布动态的用户信息
                User dynamicUser = userService.fingById(othUserId);
                UserFollow userFollow=new UserFollow();
                userFollow.setFollowId(othUserId);
                userFollow.setFansId(myId);
                int follow = userFollowService.findFollowByBothId(userFollow);
                int mutual = userFollowService.mutualAttentionFindById(userFollow);
                int countFollow = userFollowService.countFollowById(othUserId);
                int countFans = userFollowService.countFansById(othUserId);
                int countDynamic = dynamicService.countDynamicByUserId(othUserId);
                userMap.put("id",dynamicUser.getId());
                userMap.put("name",dynamicUser.getName());
                userMap.put("gender",dynamicUser.getGender());
                userMap.put("avatar",dynamicUser.getAvatar());
                userMap.put("follow", follow != 0);
                userMap.put("mutualAttention",mutual!=0);
                userMap.put("countFollow",countFollow);
                userMap.put("countFans",countFans);
                userMap.put("dynamic",countDynamic);
                mapData.put("user",userMap);
            }
        }
        if (type==2){
            if (!mapData.containsKey("user")){
                //获取发布动态的用户信息
                mapData.put("user",userService.getUserMap(myId));
            }
        }
        pageInfo.getList().forEach(list -> {
            Dynamic dynamic=(Dynamic)list;
            List<Object> imgList=new ArrayList<>();
            List<Object> tagList=new ArrayList<>();
            List<Object> remindList=new ArrayList<>();
            Map<String,Object> forwadrMap=new HashMap<>();
            Map<String,Object> map=new LinkedHashMap<>();
            Map<String,Object> othUserMap=new LinkedHashMap<>();
            if (type==1||type==0){
                //            每条动态都需要携带用户参数
                //获取发布动态的用户信息
                User dynamicUser = userService.fingById(dynamic.getUserId());
                UserFollow userFollow=new UserFollow();
                userFollow.setFollowId(dynamic.getUserId());
                userFollow.setFansId(myId);
                int follow = userFollowService.findFollowByBothId(userFollow);
                int mutual = userFollowService.mutualAttentionFindById(userFollow);
                othUserMap.put("id",dynamicUser.getId());
                othUserMap.put("name",dynamicUser.getName());
                othUserMap.put("avatar",dynamicUser.getAvatar());
                othUserMap.put("follow", follow != 0);
                othUserMap.put("mutualAttention",mutual!=0);
                map.put("user",othUserMap);
            }
            map.put("id",dynamic.getId());
            map.put("content",dynamic.getContent());
            if (dynamic.getHaveImg()== ConstantType.DYNAMIC_IMG.getType()){
                List<DynamicImg> dynamicImgs = dynamicImgService.findAllByDynamicID(dynamic.getId());
                dynamicImgs.forEach(dynamicImg -> {
                    Map<String,Object> imgMap=new LinkedHashMap<>();
                    imgMap.put("id",dynamicImg.getId());
                    imgMap.put("address",dynamicImg.getAddress());
                    imgMap.put("drder",dynamicImg.getOrder());
                    imgList.add(imgMap);
                });
            }
            if (dynamic.getHaveTag()==ConstantType.DYNAMIC_TAG.getType()){
                List<MappingTag> mappingTags = mappingTagService.findAllByDynamicId(dynamic.getId());
                mappingTags.forEach(mappingTag -> {
                    Map<String,Object> tagMap=new LinkedHashMap<>();
                    DynamicTag dynamicTag = dynamicTagService.findById(mappingTag.getTagId());
                    tagMap.put("id",dynamicTag.getId());
                    tagMap.put("content",dynamicTag.getContent());
                    tagMap.put("order",mappingTag.getOrder());
                    tagList.add(tagMap);
                });
            }
            if (dynamic.getHaveRemind()==ConstantType.DYNAMIC_REMIND.getType()){
                Remind forReminds=new Remind();
                forReminds.setType(ConstantType.REMIND_DYNAMIC.getType());
                forReminds.setParentID(dynamic.getId());
                List<Remind> reminds = remindService.getAllByParentId(forReminds);
                reminds.forEach(remind -> {
                    User user = userService.fingById(remind.getPassiveId());
                    Map<String,Object> remindMap=new LinkedHashMap<>();
                    remindMap.put("id",remind.getPassiveId());
                    remindMap.put("userName",user.getName());
                    remindMap.put("order",remind.getOrder());
                    remindList.add(remindMap);
                });
            }
            if (dynamic.getForward() != 0){
                int id = dynamic.getForward();
                Recipes recipes = foodService.getRecipes(id);
                forwadrMap.put("id",recipes.getId());
                forwadrMap.put("name",recipes.getName());
                forwadrMap.put("photo",recipes.getPhoto());
                forwadrMap.put("more",recipes.getMore());
            }
            map.put("img",imgList);
            map.put("tag",tagList);
            map.put("remind",remindList);
            map.put("type",dynamic.getType());
            map.put("forward",forwadrMap);
            //动态喜欢、评论、收藏的数量
//            喜欢
            Like like=new Like();
            like.setType(1);
            like.setParentId(dynamic.getId());
            like.setUserId(myId);
            int dynamicLike = likeService.countLike(like);
//            评论
            int commentCount=0;
            commentCount = commentCount + commentService.countComment(dynamic.getId());
            List<Integer> idList = commentService.findByDynamicIdForId(dynamic.getId());
            commentCount += idList.stream().mapToInt(id -> replyService.countReply(id)).sum();
//            收藏
            Collect collect=new Collect();
            collect.setType(2);
            collect.setParentId(dynamic.getId());
            collect.setUserId(myId);
            int collectCount = foodService.countCollect(collect);
            map.put("like",dynamicLike);
            map.put("is_like",likeService.checkLike(like) == 1);
            map.put("comment",commentCount);
            map.put("collection",collectCount);
            map.put("is_collection",foodService.checkCollect(collect)==1);
            map.put("createTime", TimeUtil.timestampFormat(dynamic.getCreateTime()));
            mapList.add(map);
        });
        mapData.put("dynamic",mapList);
        return mapData;
    }

}